package com.cgx.service.impl;

import com.cgx.dao.VersionLockDao;
import com.cgx.entity.VersionLock;
import com.cgx.service.VersionLockService;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import redis.clients.jedis.JedisCommands;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author chenguanxin
 * @date 2020-08-27 22:53
 */
@Service
public class VersionLockServiceImpl implements VersionLockService {

    @Autowired
    private VersionLockDao versionLockDao;


    @Transactional
    @Override
    public Map<String, Object> testVersionLock(String id) {
        Map<String, Object> result = new HashMap<>();
        Optional<VersionLock> versionLockOptional = versionLockDao.findById(id);
        Assert.notNull(versionLockOptional, "该id不存在");
        VersionLock versionLock = versionLockOptional.get();
        String oldVersion = versionLock.getVersion();
        String newVersion = Integer.parseInt(oldVersion) + 1 + "";
        String newValue = Integer.parseInt(versionLock.getValue()) + 1 + "";
        //  把旧版本号也加入到where条件里
        int i = versionLockDao.updateVersionLockByVersion(id, newValue, newVersion, oldVersion);
        Assert.isTrue(i > 0, "当前值版本已改变, 请重新提交");
        return result;
    }


}
